<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./a.js"></script>
</head>

<body>
    <!-- <form action="" enctype="multipart/form-data"></form> -->
    <h1>我是主页</h1>
    <input type="file" class="img" />
    <img src="" />
    <button class="btn">上传文件</button>
    <script>
        //1.图片预览  2.图片上传
        // 1.图片预览
        let imgs = document.querySelector(".img");
        imgs.onchange = function() {
            //1.通过js获取图片文件对象
            console.log(this.files[0]);
            //2.可以把图片文件对象转成base64格式
            // fileReader,js内置的类
            let fileReader = new FileReader();
            //通过fileReader把图片readAsDataURL读成base64
            fileReader.readAsDataURL(this.files[0]);
            // onload时间读完
            fileReader.onload = function() {
                console.log(fileReader.result); //result,结果
                let imgs = document.createElement("img"); //创建img标签
                imgs.src = fileReader.result;
                document.body.appendChild(imgs); //添加到body里面
            };
        };
        //上传图片到服务器
        let onbtn = document.querySelector(".btn");
        onbtn.onclick = function() {
            //做文件的上传
            //获取文件
            let img = imgs.file[0];
            //FormData
            let form = new FormData();
            form.append("myimg", img);
            let xhr = new XMLHttpRequest();
            //文件上传只支持 POST
            xhr.open("post", "/postfile");
            xhr.onload = function() {
                console.log(xhr.responseText);
            };
            xhr.send(form);
        };
    </script>
</body>

</html>